package task

import (
	cfg "db_ping/config"
	e "db_ping/err"
	"db_ping/switchdb"
	"github.com/robfig/cron"
)

func Start(config *cfg.Config) {
	c := cron.New()
	for _, db := range config.Yc.Db {
		run := &cfg.RunSqlConfig{
			Username: db.Username,
			Password: db.Password,
			Url:      db.Url,
		}
		_ = c.AddFunc(config.Yc.Task.Cron, taskDbFuncName(&db, run))
	}
	//启动计划任务
	c.Start()
}

func taskDbFuncName(s *cfg.SqlConfig, r *cfg.RunSqlConfig) func() {
	return func() {
		errNumber := e.GetErrNumber(s.TaskName)
		if errNumber == 3 {
			switchdb.SwitchBackDataSource(s, r)
		} else {
			db := cfg.GetConnection(s, r)
			defer db.Close()
		}
	}
}
